//
//  SchoolAddUploadHornViewController.swift
//  Venus
//
//  Created by qurongxiang on 2018/8/8.
//  Copyright © 2018年 zhaowang. All rights reserved.
//

import UIKit
import MobileCoreServices
import SwiftyJSON
import AVFoundation
import Photos

class SchoolAddUploadHornViewController: BaseViewController {
    var type:Int = 0 //0图片 1视频
    fileprivate lazy var addVideoView = AddVideoView(frame: CGRect.zero)
    var imagePickInfo:[UIImagePickerController.InfoKey : Any] =  [UIImagePickerController.InfoKey : Any]()
    var currentVideoSize:Int64 = 0
    var currentVideoTime:Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupUI()
    }
}

extension SchoolAddUploadHornViewController {
    @objc func clickBtn(btn: UIButton) {
        var data:Data = Data()
        if type == 0 {
            guard let img = imagePickInfo[UIImagePickerController.InfoKey.originalImage] as? UIImage else {
                hudLoadMessage("请选择图片")
                return }
            data = img.jpegData(compressionQuality: 0.5)!
        }else {
            guard let url = imagePickInfo[UIImagePickerController.InfoKey.mediaURL] as? URL else {
                hudLoadMessage("请选择视频")
                return }
            let asset = AVURLAsset(url:url)
            let time: CMTime = asset.duration
            let s = CMTimeGetSeconds(time)
            if s  >= 15 * 60 {
                hudLoadMessage("不得大于15分钟")
                return
            }else if s < 9{
                hudLoadMessage("不得小于10秒")
                return
            }
            data = try! Data.init(contentsOf: url)
            currentVideoSize = Int64(data.count)
            currentVideoTime = lroundf(Float(s))
        }
        
        addVideoView.progressView.isHidden = false
        let uploadOptionVideo = QNUploadOption.init(mime: "video/mp4", progressHandler: { [weak self](key, percent:Float) in
            DispatchQueue.main.async(execute: {
                self?.addVideoView.progressView.progress = percent
            })
            }, params: nil, checkCrc: false, cancellationSignal: nil)
        
        
        let uploadOptionImage = QNUploadOption.init(mime: "image/jpeg", progressHandler: { [weak self] (key, percent:Float) in
            DispatchQueue.main.async(execute: {
                self?.addVideoView.progressView.progress = percent
            })
            }, params: nil, checkCrc: false, cancellationSignal: nil)
        
        self.hudLoad()
        
        var myUrl:String = ""
        if self.type == 0 { //图片
            myUrl = kHost + kgetImgToken
        }else { // 视频
            myUrl = kHost + kgetVideoToken
        }
        TempNetTool.get(myUrl, parameters: ["timestamp":"11","sign":"22"], progress: nil, success: { [weak self](result) in
            let json = JSON(result ?? "")
            let token = json["uptoken"].string
            let uploadManage = QNUploadManager.init()
            
            if self?.type == 0 {
                uploadManage?.put(data, key: nil, token: token, complete: { [weak self] (info, key, result) in
                    
                    let json = JSON(result as Any)
                    let url = json["key"].stringValue
                    self?.upload(path: kqnImageHost + url)
                    self?.addVideoView.progressView.isHidden = true
                    }, option: uploadOptionImage)
            }else {
                uploadManage?.put(data, key: nil, token: token, complete: { [weak self] (info, key, result) in
                    
                    let json = JSON(result as Any)
                    let url = json["key"].stringValue
                    self?.upload(path: kqnVideoHost + url)
                    self?.addVideoView.progressView.isHidden = true
                    }, option: uploadOptionVideo)
            }
            
        }) { [weak self](error) in
            self?.hudHide()
            self?.hudLoadMessage("网络异常")
        }
    }
    
    
    fileprivate func upload(path:String) {
        
        let dict = [["fileType":self.type,
                     "path":path,
                     "videoSize": currentVideoSize,
                     "videoTime": currentVideoTime,
                     "institutionId":UserInfo.shareInstance.userModel().institutionId,
                     "title":addVideoView.nameTextField.text!
            ] as [String : Any]]
        TempNetTool.post(kHost + kgaddInstitutionResource + String().apiF(time: "1", sign: "1"), parameters: dict, progress: nil, success: { [weak self](result) in
            self?.hudHide()
            self?.navigationController?.popViewController(animated: true)
        }) { [weak self] (error) in
            
            print(Thread.current,"zzzzzz")
            self?.hudHide()
            self?.hudLoadMessage("网络异常")
            
        }
    }
    
    
    @objc func clickUpBtn(btn: UIButton) {
        if (addVideoView.nameTextField.text?.count)! <= 0 {
            self.hudLoadMessage("请先输入标题吧")
            return
        }
        if type == 1 {
            photoClick()
        }else {
            photoClickImg()
        }
    }
}

extension SchoolAddUploadHornViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func photoClick() {
        
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary)  {
            self.hudLoadMessage("请检查相册权限")
            return
        }
        let photoVc = UIImagePickerController()
        photoVc.sourceType = .photoLibrary
        photoVc.mediaTypes =  [kUTTypeMovie as String]
        photoVc.delegate = self
        present(photoVc, animated: true, completion: nil)
    }
    func photoClickImg() {
        let pick:UIImagePickerController = UIImagePickerController()
        pick.delegate = self
        pick.sourceType = UIImagePickerController.SourceType.photoLibrary
        pick.allowsEditing = true
        present(pick, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated:true, completion:nil)
        imagePickInfo = info
        
        if self.type == 0 {
            self.addVideoView.titleLabel.text = "图片成功选择 👇上传"
        }else {
            self.addVideoView.titleLabel.text = "视频成功选择 👇上传"
        }
    }
}



extension SchoolAddUploadHornViewController {
    func setupUI() {
        title = type == 0 ? "添加图片":"添加视频"
        if type == 0 {
            addVideoView.titleLabel.text = "选择要上传的图片"
            addVideoView.infoLabel.isHidden = true
        }else {
            addVideoView.titleLabel.text = "选择要上传的视频"
            addVideoView.infoLabel.isHidden = false
        }
        view.addSubview(addVideoView)
        
        addVideoView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(LayoutCommon.navHeight)
            make.left.right.equalToSuperview()
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
            } else {
                make.bottom.equalToSuperview()
            }
        }
        addVideoView.upBtn.addTarget(self, action: #selector(clickUpBtn(btn:)), for: .touchUpInside)
        addVideoView.btn.addTarget(self, action: #selector(clickBtn(btn:)), for: .touchUpInside)
    }
}
